package com.wsc.wsckeeper.activities;

import java.io.IOException;

import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.wsc.wsckeeper.R;
import com.wsc.wsckeeper.activities.base.BaseActivity;
import com.wsc.wsckeeper.listeners.TextWatcherImpl;
import com.wsc.wsckeeper.managers.FileServiceManager;
import com.wsc.wsckeeper.managers.ResourceManager;
import com.wsc.wsckeeper.utils.inputfilters.ExportInputFilter;

public class ExportActivity extends BaseActivity {
	private static final int MIN_LENGTH = 3;
	private static final int MAX_LENGTH = 20;

	private EditText etName;
	private Button btSave;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_export);
		super.onCreate(savedInstanceState);
	}

	@Override
	public void initComponents() {
		etName = (EditText) findViewById(R.id.name);
		btSave = (Button) findViewById(R.id.action);
	}

	@Override
	public void initValues() {
		getActionBar().setSubtitle(R.string.action_export);

		etName.setFilters(new InputFilter[] { new ExportInputFilter() });
		btSave.setEnabled(false);
	}

	@Override
	public void initListeners() {
		btSave.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				try {
					if (isValidFields()) {
						FileServiceManager.getInstance().backupDatabase(etName.getText().toString());
						finish();
					}
				} catch (IOException e) {
					showExceptionAsDialog(e);
				}
			}
		});

		etName.addTextChangedListener(new TextWatcherImpl() {
			@Override
			public void afterTextChanged(Editable s) {
				btSave.setEnabled(true);
				etName.setError(null);
			}
		});
	}

	private boolean isValidFields() {
		boolean isValid = true;
		if (etName.getText().toString().length() < MIN_LENGTH) {
			etName.setError(ResourceManager.getStringValue(R.string.export_existing_min));
			isValid = false;
		} else {
			if (etName.getText().toString().length() > MAX_LENGTH) {
				etName.setError(ResourceManager.getStringValue(R.string.export_existing_max));
				isValid = false;
			}
		}
		return isValid;
	}
}
